package com.kiss.rpc.compress.impl;

import com.kiss.rpc.compress.Compressor;
import com.kiss.rpc.exceptions.CompressException;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Slf4j
public class GzipCompressor implements Compressor {

    @Override
    public byte[] compress(byte[] data) {
        try (
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gos = new GZIPOutputStream(baos);
        ){
            gos.write(data);
            gos.finish();
            byte[] compressed = baos.toByteArray();
            if (log.isDebugEnabled()) {
                log.debug("对字节数组进行了压缩长度由【{}】压缩至【{}】.", data.length, compressed.length);
            }
            return compressed;
        }
        catch (Exception e) {
            log.error("对字节数组进行压缩时发生异常",e);
            throw new CompressException(e);
        }
    }

    @Override
    public byte[] decompress(byte[] data) {
        try (
                ByteArrayInputStream bais = new ByteArrayInputStream(data);
                GZIPInputStream gis = new GZIPInputStream(bais);
                ){
            byte[] decompressed = gis.readAllBytes();
            if (log.isDebugEnabled()) {
                log.debug("对字节数组进行了解压缩，长度由【{}】变为了【{}】", data.length, decompressed.length);
            }
            return decompressed;
        }
        catch (Exception e) {
            log.error("对字节数组进行解压缩时发生异常",e);
            throw new CompressException(e);
        }
    }
}
